package vtt.android.dapanhc.activities.fragments;

import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;

import vtt.android.dapanhc.Constants;
import vtt.android.dapanhc.R;
import vtt.android.dapanhc.activities.TopActivity;
import vtt.android.dapanhc.database.AnswerDAO;
import vtt.android.dapanhc.dialogs.DialogManager;
import vtt.android.dapanhc.dialogs.DialogManager.IDialogListener;
import vtt.android.dapanhc.entities.Answer;
import vtt.android.dapanhc.utils.VttDateUtils;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.ads.AdView;

public class TopChallengeFragment extends BaseWebFragment implements IDialogListener {
	
	public interface Listener {
        public void onSubmitScore(int score);
    }

    Listener mListener = null;
    boolean mShowSignIn = true;
    
    private DialogManager dialogManager;
    private static ProgressBar progressBar;
    private static AnswerDAO answerDAO;
	private TextView tvRemainTime;
	private TextView tvExtraPoint;
	private WebView mWebView;
	private SharedPreferences sharedPreferences;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	dialogManager = new DialogManager(getActivity());
    	dialogManager.addDialogListener(this);
    	
    	answerDAO = AnswerDAO.getInstance(getActivity());
		answerDAO.open();
		
		sharedPreferences = getActivity().getSharedPreferences(Constants.SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
    }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_top_challenge, container, false);
		
		progressBar = (ProgressBar) v.findViewById(R.id.progressbar1);
		
		tvRemainTime = (TextView) v.findViewById(R.id.tv_remain_time);
		tvExtraPoint = (TextView) v.findViewById(R.id.tv_extra_point);
		// init event for button
		mWebView = (WebView) v.findViewById(R.id.webView1);
		setupWebview(mWebView, new MyWebChromeClient(), new WebClient(), new AndroidBridge());
		
		mWebView.loadUrl("file:///android_asset/html/index.html");
		// Look up the AdView as a resource and load a request.
		AdView adView = (AdView) v.findViewById(R.id.adView);
	    loadAdmob(adView);
	    
        return v;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		VttGA.sendView(getActivity(), "/challenge_screen");
	}
	
	class MyWebChromeClient extends WebChromeClient {
		public void onProgressChanged(WebView view, int progress) {
			// update the progressBar
			progressBar.setProgress(progress);
			if (progress >= 100) {
				progressBar.setProgress(100);
				progressBar.setVisibility(View.GONE);
			}
		}
	}
	/*
	 * Android bridge
	 */
	class AndroidBridge {
		
		MediaPlayer player;
		
		public AndroidBridge() {
			// prepare source at the first time
			player = new MediaPlayer();
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			try {
				player.setDataSource("http://www.hellochao.vn/play_sound.php?sid=e4da5b7fbbce234527779b0674a318Ms&type=11");
				player.prepareAsync();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		@JavascriptInterface
		public void updateTimeCounter(final String timeCount,final String extraPoint){
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					tvRemainTime.setText("Time: " + timeCount);
					tvExtraPoint.setText("Bonus: " + extraPoint);
				}
			});
		}

		@JavascriptInterface
		public void playAudio(String url){
			log.d("VTT>>> playAudio " + url);
			
			if(!VttUtils.checkNetworkConnection(getActivity())){
				dialogManager.showAlertDialog(Constants.DIALOG_INTERNET_ALERT, getString(R.string.msg_title_notice), getString(R.string.msg_network_error), false);
				return;
			}
			
			if(player != null){
				player.release();
				player = null;
			}
			
			player = new MediaPlayer();
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			try {
				player.setDataSource(url);
				player.setOnErrorListener(new OnErrorListener() {
					@Override
					public boolean onError(MediaPlayer mp, int what, int extra) {
						String errMsg = "Can not play sound : what " + what + "; extra " + extra + "; device info : " + VttUtils.getDeviceInfo();
						VttGA.sendException(getActivity(), errMsg);
						log.e("VTT>>> onError " + errMsg);
						return false;
					}
				});
				player.setOnPreparedListener(new OnPreparedListener() {
					@Override
					public void onPrepared(MediaPlayer mp) {
						mp.start();
					}
				});
				player.prepareAsync();
			} catch (Exception e) {
				Toast.makeText(getActivity(), 
						R.string.msg_err_play_audio,
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		}
		
		@JavascriptInterface
		public void saveAnswer(String sid, String suggestion, String en, String vn, String soundUrl){
			//log.d("VTT>>> AndroidBridge saveAnswer " + String.format("('%s', '%s', '%s', '%s', '%s', '%s');", sid,suggestion, en, vn, soundUrl, getCurrentDayString()));
			answerDAO.saveAnswer(new Answer(sid, suggestion, en, vn, soundUrl, VttDateUtils.getCurrentDayString(sharedPreferences)));
		}
		
		@JavascriptInterface
		public boolean isNewDate(){
			String curDay = sharedPreferences.getString(Constants.SHARE_KEY_CURRENT_DAY, "19000101");
			return answerDAO.checkNewDate(curDay);
		}
		
		@JavascriptInterface
		public String loadOldAnswer(){
			try {
				// load current day for challenging
				String yyyyMMdd = VttDateUtils.getCurrentDayString(sharedPreferences);
				JSONArray answerArray = answerDAO.loadAnswerByDate(yyyyMMdd);
				//log.d("VTT>>> answerArray before " + answerArray);
				// random array
				answerArray = shuffleJsonArray(answerArray);
				//log.d("VTT>>> answerArray after " + answerArray);
				return answerArray.toString();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@JavascriptInterface
		public JSONArray shuffleJsonArray(JSONArray array) throws JSONException {
			// Implementing Fisher–Yates shuffle
			Random rnd = new Random();
			for (int i = array.length() - 1; i >= 0; i--) {
				int j = rnd.nextInt(i + 1);
				// Simple swap
				Object object = array.get(j);
				array.put(j, array.get(i));
				array.put(i, object);
			}
			return array;
		}
		
		@JavascriptInterface
		public boolean isChallengeMode(){
			return true;
		}
		
		@JavascriptInterface
		public int getTimeChallenge(){
			return Constants.NUMBER_TIME_CHALLENGE;
		}
		
		@JavascriptInterface
		public void submitScore(int score){
			mListener.onSubmitScore(score);
		}
		
		// GA
		@JavascriptInterface
		public void sendEvent(final String action){
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					try{
						VttGA.sendEvent(getActivity(), "UserClick", action, "", 0);
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			});
		}
		
		// show log
		@JavascriptInterface
		public void log(String tag, String msg){
			log.d("VTT>>> " + tag + " : " + msg);
		}
		
		// show dialog
		@JavascriptInterface
		public void showDialog(String title, String message){
			dialogManager.showAlertDialog("", title, message, false);
		}
		
		// show dialog
		@JavascriptInterface
		public void showScoreDialog(final String cSentence,final String cPoint,final String finishTime,final String ponus,final String total){
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					try{
						dialogManager.showScoreResultDialog(Constants.DIALOG_SCORE_ALERT, cSentence, cPoint, finishTime, ponus, total);
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			});
		}
	}
	
	class WebClient extends WebViewClient {
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			progressBar.setVisibility(View.VISIBLE);
			progressBar.setProgress(0);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			return super.shouldOverrideUrlLoading(view, url);
		}
	}

	public void setListener(Listener l) {
        mListener = l;
    }
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		log.i("VTT>>> " + "onDestroy");
		mWebView.destroy();
	}

	@Override
	public void onOkClick(String dialogName) {
		
	}

	@Override
	public void onCancelClick(String dialogName) {
		if(Constants.DIALOG_SCORE_ALERT.equals(dialogName)){
			log.d("VTT>>> onCancelClick popBackStack()");
			getActivity().getSupportFragmentManager().popBackStack();
		}
	}

	@Override
	public void onViewLeaderBoardClick(String dialogName) {
		((TopActivity)getActivity()).onShowLeaderboardsRequested();
		getActivity().getSupportFragmentManager().popBackStack();
	}

}
